﻿using Common;
using Dal;
using Entity;
using Entity.ViewModel.UserInfo;
using IBll;
using IDal;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Utilities.Encoders;
using System.Runtime.CompilerServices;
using System.Security.Principal;

namespace Bll
{
    /// <summary>
    /// 用户业务逻辑层
    /// </summary>
    public class UserInfoBll : IUserInfoBll
    {
        IUserInfoDal _userInfoDal;

        public UserInfoBll(IUserInfoDal userInfoDal)
        {
            _userInfoDal = userInfoDal;
        }


        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool CreateUserInfo(string account, string password, out string msg)
        {
            UserInfo userInfo = _userInfoDal.GetUserInfos(u => u.Account == account).FirstOrDefault();

            if (userInfo != null)
            {
                msg = "账号已经存在";
                return false;
            }

            //密码使用MD5加密
            string md5Password = MD5Helper.MD5Encrypt64(password);

            UserInfo entity = new UserInfo();
            //创建guid 赋值给用户id，目的是保证id唯一
            entity.Id = Guid.NewGuid().ToString();
            entity.Account = account;
            entity.UserName = account;
            entity.PassWord = md5Password;
            entity.CreateTime = DateTime.Now;

            //调用数据访问层创建用户
            bool isSuccess = _userInfoDal.CreateUserInfo(entity);
            if (isSuccess)
            {
                msg = "成功";
            }
            else
            {
                msg = "失败";
            }
            return isSuccess;
        }


        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="phone"></param>
        /// <param name="sex"></param>
        /// <param name="email"></param>
        /// <param name="departmentId"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool CreateUserInfo(string userName, string account, string phone, int sex, string email, string departmentId, out string msg)
        {
            //验证账号是否存在
            UserInfo userInfo = _userInfoDal.GetUserInfos(u => u.Account == account).FirstOrDefault();

            if (userInfo != null)
            {
                msg = "账号已经存在";
                return false;
            }

            string md5Password = MD5Helper.MD5Encrypt64("123456");

            bool isSuccess = _userInfoDal.CreateUserInfo(new UserInfo()
            {
                Id = Guid.NewGuid().ToString(),
                UserName = userName,
                Account = account,
                CreateTime = DateTime.Now,
                Email = email,
                PassWord = md5Password,
                PhoneNum = phone,
                Sex = sex
            });

            if (isSuccess)
            {
                msg = "成功";
                return true;
            }
            else
            {
                msg = "失败";
                return false;
            }
        }

        /// <summary>
        /// 软删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteUserInfo(string id)
        {
            UserInfo userInfo = _userInfoDal.GetUserInfosDbSet().FirstOrDefault(u => u.Id == id);
            if (userInfo == null)
            {
                return false;
            }

            userInfo.IsDelete = true;

            return _userInfoDal.UpdateUserInfo(userInfo);
        }

        /// <summary>
        /// 批量软删除用户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DeleteUserInfos(List<string> ids)
        {
            foreach (var id in ids)
            {
                UserInfo userInfo = _userInfoDal.GetUserInfosDbSet().FirstOrDefault(u => u.Id == id);
                if (userInfo == null)
                {
                    return false;
                }

                userInfo.IsDelete = true;

                _userInfoDal.UpdateUserInfo(userInfo);
            }

            return true;
        }

        ///// <summary>
        ///// 头像下载
        ///// </summary>
        ///// <param name="userId"></param>
        ///// <param name="fileName"></param>
        ///// <returns></returns>
        //public byte[] DownloadImg(string userId, out string fileName)
        //{
        //    FilesInfo filesInfo = _filesInfoDal.GetDbSet().OrderByDescending(f => f.CreateTime)
        //         .FirstOrDefault(f => f.RelationId == userId && f.Category == 1);

        //    if (filesInfo == null)
        //    {
        //        fileName = "";
        //        return new byte[0];
        //    }
        //    else
        //    {
        //        //获取磁盘上文件的路径
        //        string filePath = filesInfo.NewFileName.Replace("/", "\\");
        //        filePath = @"D:\RepositorySys\RepositorySys\wwwroot" + filePath;

        //        using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        //        {
        //            //装数据的字节数组
        //            byte[] buffer = new byte[fileStream.Length];

        //            //把流中的文件内容装进buffer数组里
        //            fileStream.Read(buffer, 0, (int)fileStream.Length);

        //            fileName = filesInfo.OldFileName;

        //            return buffer;
        //        }
        //    }
        //}


        /// <summary>
        ///  获取下拉选备选数据
        /// </summary>
        /// <returns></returns>
        public object GetSelectOptionList()
        {
            return _userInfoDal.GetUserInfosDbSet().Where(u => !u.IsDelete).Select(d => new
            {
                d.Id,
                d.UserName
            }).ToList();
        }

        /// <summary>
        /// 根据用户id获取用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public UserInfoViewModel GetUserInfoById(string userId)
        {
            UserInfo userInfo = _userInfoDal.GetUserInfos(u => u.Id == userId).FirstOrDefault();
            ////查询用户头像的信息(Category = 1是头像，RelationId关系就是用户id)
            //FilesInfo filesInfo = _filesInfoDal.GetDbSet().OrderByDescending(f => f.CreateTime)
            //    .FirstOrDefault(f => f.Category == 1 && f.RelationId == userId);



            UserInfoViewModel model = new UserInfoViewModel();

            if (userInfo != null)
            {
                model.Id = userInfo.Id;
                model.Account = userInfo.Account;
                model.Email = userInfo.Email;
                model.PhoneNum = userInfo.PhoneNum;
                model.Sex = userInfo.Sex;
                model.UserName = userInfo.UserName;
            }

            //if (filesInfo != null)
            //{
            //    model.Imgs = filesInfo.NewFileName;
            //}

            return model;
        }


        /// <summary>
        /// 获取用户集合
        /// </summary>
        public List<GetUserInfoListViewModel> GetUserInfoList(string userName, string phone, int page, int limit, out int count)
        {

            var queryable = from u in _userInfoDal.GetDbSet().Where(u => !u.IsDelete)
                            select new
                            {
                                Id = u.Id,
                                UserName = u.UserName,
                                CreateTime = u.CreateTime,
                                PhoneNum = u.PhoneNum,
                                Sex = u.Sex,
                                Email = u.Email
                            };


            if (!string.IsNullOrEmpty(userName))
            {
                queryable = queryable.Where(u => u.UserName.Contains(userName));
            }

            if (!string.IsNullOrEmpty(phone))
            {
                queryable = queryable.Where(u => u.PhoneNum.Contains(phone));
            }


            //查询总条数
            count = queryable.Count();

            List<GetUserInfoListViewModel> list = queryable.OrderByDescending(u => u.CreateTime)
                .Skip((page - 1) * limit)
                .Take(limit)
                .ToList()
                .Select(u =>
                 new GetUserInfoListViewModel
                 {
                     Id = u.Id,
                     UserName = u.UserName,
                     CreateTime = u.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                     PhoneNum = u.PhoneNum,
                     Sex = u.Sex == 0 ? "女" : "男",
                     Email = u.Email
                 }).ToList();

            return list;
        }

        /// <summary>
        /// 验证登录
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool Login(string account, string password, out UserInfo userInfo, out string msg)
        {
            //创建数据访问层对象
            //UserInfoDal userInfoDal = new UserInfoDal();

            //根据账号找出用户的信息
            UserInfo entity = _userInfoDal.GetUserInfos(u => u.Account == account).FirstOrDefault();

            //先查账号是否正确
            if (entity == null)
            {
                msg = "账号不存在";
                userInfo = null;
                return false;
            }

            //加密用户输入的密码
            string md5Password = MD5Helper.MD5Encrypt64(password);

            if (entity.PassWord == md5Password)
            {
                msg = "成功";
                userInfo = entity;
                return true;
            }
            else
            {
                msg = "密码错误";
                userInfo = null;
                return false;
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool UpdatePassword(string userId, string oldPassword, string newPassword, out string msg)
        {
            UserInfo userInfo = _userInfoDal.GetUserInfos(u => u.Id == userId).FirstOrDefault();
            if (userInfo == null)
            {
                msg = "用户参数有误";
                return false;
            }

            //加密后的旧密码
            string oldPwd = MD5Helper.MD5Encrypt64(oldPassword);
            if (oldPwd != userInfo.PassWord)
            {
                msg = "旧密码有误";
                return false;
            }


            //加密后的新密码
            string newPwd = MD5Helper.MD5Encrypt64(newPassword);
            userInfo.PassWord = newPwd;

            bool isSuccess = _userInfoDal.UpdateUserInfo(userInfo);
            if (isSuccess)
            {
                msg = "成功";
                return true;
            }
            else
            {
                msg = "修改失败";
                return false;
            }
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userName"></param>
        /// <param name="phoneNum"></param>
        /// <param name="email"></param>
        /// <param name="sex"></param>
        /// <returns></returns>
        public bool UpdateUserInfo(string userId, string userName, string phoneNum, string email, int sex, string departmentId)
        {
            //根据账号找出用户的信息
            UserInfo entity = _userInfoDal.GetUserInfos(u => u.Id == userId).FirstOrDefault();
            if (entity == null)
            {
                return false;
            }

            entity.UserName = userName;
            entity.PhoneNum = phoneNum;
            entity.Email = email;
            entity.Sex = sex;

            //调用数据访问层
            bool isSucess = _userInfoDal.UpdateUserInfo(entity);
            return isSucess;
        }


        ///// <summary>
        ///// 上传头像
        ///// </summary>
        ///// <param name="stream"></param>
        ///// <param name="fileName"></param>
        ///// <param name="userId"></param>
        ///// <param name="msg"></param>
        ///// <returns></returns>
        ///// <exception cref="NotImplementedException"></exception>
        //public bool UploadImg(Stream stream, string fileName, string userId, out string msg)
        //{
        //    //获取文件的拓展名
        //    string extension = Path.GetExtension(fileName);

        //    //新文件名（磁盘最终存的时候的名字）
        //    string newFileName = DateTime.Now.Ticks.ToString() + extension;


        //    try
        //    {
        //        //1、创建文件到磁盘中
        //        using (FileStream fileStream = new FileStream($@"D:\RepositorySys\RepositorySys\wwwroot\images\{newFileName}", FileMode.Create, FileAccess.Write))
        //        {
        //            stream.CopyTo(fileStream);
        //        }

        //        //2、创建filesInfo实例
        //        FilesInfo filesInfo = new FilesInfo()
        //        {
        //            Id = Guid.NewGuid().ToString(),
        //            Category = 1,//头像
        //            CreateTime = DateTime.Now,
        //            Creator = userId,
        //            Extension = extension,
        //            Length = stream.Length,
        //            //新文件名（磁盘最终存的时候的名字）
        //            NewFileName = $"/images/{newFileName}",
        //            OldFileName = fileName,
        //            //关系id就是当前登录人的id（头像就是他的）
        //            RelationId = userId
        //        };

        //        //添加到数据库
        //        bool isSuccess = _filesInfoDal.CreateEntity(filesInfo);

        //        if (isSuccess)
        //        {
        //            msg = "成功";
        //            return true;
        //        }
        //        else
        //        {
        //            msg = "失败";
        //            return false;
        //        }
        //    }
        //    catch (Exception)
        //    {
        //        msg = "失败";
        //        return false;
        //    }
        //}
    }
}